package cj.web.login.controllers;

import java.io.File;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import cj.web.admin.constants.Constants;
import cj.web.admin.constants.UserTypeEnum;
import cj.web.admin.dao.ConfigInfoDAO;
import cj.web.admin.dao.MemuInfoDAO;
import cj.web.admin.dao.UserInfoDAO;
import cj.web.admin.dao.UserRoleRefDAO;
import cj.web.admin.domain.ConfigInfo;
import cj.web.admin.domain.UserInfo;
import cj.web.admin.domain.UserRoleRef;
import cj.web.admin.utils.Base64;
import cj.web.admin.utils.DateUtils;
import cj.web.admin.utils.MD5Security;
import cj.web.admin.utils.ReadConfigProperties;
import cj.web.admin.utils.ReturnUUID;
import cj.web.admin.utils.RsaUtil;
import cj.web.tb.constants.RaterTypeEnum;
import cj.web.tb.constants.StatusEnum;
import cj.web.tb.dao.TBAreaDAO;
import cj.web.tb.dao.TBRaterRegistrationDAO;
import cj.web.tb.dao.TBSchoolDAO;
import cj.web.tb.dao.TBSchoolRegistrationDAO;
import cj.web.tb.domain.TBRaterRegistration;
import cj.web.tb.domain.TBSchool;
import cj.web.tb.domain.TBSchoolRegistration;

@Path("")
public class LoginController extends BaseController{
	
	protected static final Log logger = LogFactory.getLog(LoginController.class);
	
	//教室角色Code
	private final static String TEACHER = "TEACHER";
	//学校实名申报角色Code
	private final static String SCHOOL = "SCHOOL";
	
	@Autowired
	private UserInfoDAO userInfoDao;
	@Autowired
	private MemuInfoDAO memuInfoDao;
	@Autowired
	private ConfigInfoDAO configInfoDao;
	@Autowired
	private TBRaterRegistrationDAO tBRaterRegistrationDao;
	@Autowired
	private TBSchoolDAO tBSchoolDAO;
	@Autowired
	private TBSchoolRegistrationDAO tBSchoolRegistrationDao;
	@Autowired
	private TBAreaDAO tBAreaDao;
	@Autowired
	private UserRoleRefDAO userRoleRefDao;
	
	@Get("")
    public String main() throws InterruptedException {
        return "/views/index.vm";
    }
	
	/**
	 * 判断系统级权限
	 * @return
	 * @throws Exception 
	 */
	private boolean querySecurityKey() throws Exception{
		String key = configInfoDao.querySecurityKey();
		
		if(key==null || "".equals(key)){
			return false;
		}
		String showDate = RsaUtil.decryptByPrivateKey(key);
		
		if(DateUtils.compareDateWithNow(DateUtils.parse(showDate, DateUtils.DATE_SMALL_STR))>=0){
			return true;
		}else{
			return false;
		}
	}
	
	@Post("login")
	public String login(Model model,@Param("useraccount") String account,@Param("pwd") String pwd,
			HttpServletRequest request,HttpServletResponse response){
		try {
			
			if(!querySecurityKey()){
				return "r:sk/show";
			}
			
			UserInfo userInfo = userInfoDao.queryByAP(account);
			
			if(userInfo==null){
				model.add("msg","无此用户");
				return "/views/index.vm";
			}
			else{
//				if(userInfo.getPwd().equals((MD5Security.md5(pwd)))){
				if(userInfo.getPwd().equals(pwd)){
					List<String> memunamelis = userInfoDao.queryByMemu(userInfo.getId());
					
					String memuname="@";
					for(String str:memunamelis)
					{
						memuname+=str+"@";
					}
					addCookie(response, "memuname", memuname);
					addCookie(response, "account", account);
					addCookie(response, "userId", String.valueOf(userInfo.getId()));
					addCookie(response, "name", Base64.getBase64(userInfo.getName()));
					addCookie(response, "_token_", MD5Security.returnSingKey(account));//种植的Key
				}
				else{
					model.add("msg","密码不正确");
					return "/views/index.vm";
				}
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return "/views/index.vm";
		}
		
		return "r:index";
    }

	
	@Get("logout")
    public String logout(HttpServletRequest request,HttpServletResponse response){
		removeCookie(response, "memuname");
		removeCookie(response, "account");
		removeCookie(response, "userId");
		removeCookie(response, "name");
		removeCookie(response, "_token_");
		return "/views/index.vm";
    }
	
	@Get("index")
    public String index(Model model,HttpServletRequest request) {
		model.add("account",returnSessionObj(request).getAccount());
        return "/views/main.vm";
    }
	
	/**
	 * 专家注册
	 * @return
	 */
	@Get("registerRater")
    public String registerRaterPage(Model model) {
		model.add("typelis",EnumSet.allOf(RaterTypeEnum.class));
        return "/views/registerRater.vm";
    }
	
	/**
	 * 学校注册
	 * @return
	 */
	@Get("registerSchool")
    public String registerSchoolPage(Model model) {
		List<String> areaNameLis = tBAreaDao.queryAreaNameAll();
		
		model.add("arealis", areaNameLis);
        return "/views/registerSchool.vm";
    }
	
	
	@Post("registerRaterCreate")
	public synchronized String registerRaterCreate(Model model,TBRaterRegistration tBRaterRegistration,@Param("uploadimage") MultipartFile file,HttpServletRequest request){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		try {
			
			int size = userInfoDao.queryByAccount(tBRaterRegistration.getAccount());
			
			if(size>0){
				//已存在
				jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
			}else{
				UserInfo userInfo = new UserInfo();
				userInfo.setAccount(tBRaterRegistration.getAccount());
				userInfo.setName(tBRaterRegistration.getAccount());
				userInfo.setPwd(tBRaterRegistration.getPwd());
				userInfo.setType(UserTypeEnum.teacher.getValue());
				userInfo.setState(Constants.portal.userState.state_0);
				userInfo.setDeleteFlag(Constants.deleteFlag.deleteFlag_1);
				userInfo.setCreateUser(tBRaterRegistration.getAccount());
				userInfo.setUpdateUser(tBRaterRegistration.getAccount());
				int userId = userInfoDao.create(userInfo);
				
				//添加角色-TEACHER
				List<ConfigInfo> ci = configInfoDao.queryByCode(TEACHER);
				
				if(ci!=null && ci.size()>0){
					UserRoleRef obj = new UserRoleRef();
					obj.setUserId(userId);
					obj.setRoleId(Integer.parseInt(ci.get(0).getValue()));
					userRoleRefDao.create(obj);
				}
				
				// 判断文件是否为空  
		        if (!file.isEmpty()) {  
		            try {  
		                // 文件保存路径  
		            	String path = ReadConfigProperties.getValue("uploadFilePath");
		            	//判断文件是否存在，不存在创建文件
		            	Map rep = ReturnUUID.getFolder(path);
		            	path = rep.get("allpath").toString();//所在的全路径
		            	//文件名
		                String fileName =  ReturnUUID.getName(file.getOriginalFilename()); 
		                // 转存文件  
		                file.transferTo(new File(path+"/"+fileName));  
		                jo.put("filePath", rep.get("filepath")+"/"+fileName);
		                
		                tBRaterRegistration.setPhoto(rep.get("filepath")+"/"+fileName);//文件路径
		            } catch (Exception e) {  
		                e.printStackTrace();  
		                jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		            }  
		        } 
		        tBRaterRegistration.setUserId(userId);
		        tBRaterRegistration.setStatus(StatusEnum.TYPE1.getValue());
				tBRaterRegistration.setCreateUser(tBRaterRegistration.getAccount());
				tBRaterRegistration.setUpdateUser(tBRaterRegistration.getAccount());
				tBRaterRegistrationDao.create(tBRaterRegistration);
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	@Post("registerSchoolCreate")
	public synchronized String registerSchoolCreate(Model model,TBSchoolRegistration tBSchoolRegistration,@Param("uploadimage") MultipartFile file,HttpServletRequest request) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		try {
			int size = userInfoDao.queryByAccount(tBSchoolRegistration.getAccount());
			
			if(size>0){
				//已存在
				jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
			}else{
				
				TBSchool tBSchoolObj = tBSchoolDAO.
		        		queryByAreaName(tBSchoolRegistration.getAreaName(), tBSchoolRegistration.getSchoolName());
				//判断申报学校是否重复
				int tbSchoolSize = tBSchoolRegistrationDao.queryByTbSchoolIdSize(tBSchoolObj.getId());
				if(tbSchoolSize>0){
					jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
					return "@"+jo.toString();
				}
				
				UserInfo userInfo = new UserInfo();
				userInfo.setAccount(tBSchoolRegistration.getAccount());
				userInfo.setName(tBSchoolRegistration.getAccount());
				userInfo.setPwd(tBSchoolRegistration.getPwd());
				userInfo.setType(UserTypeEnum.school.getValue());
				userInfo.setState(Constants.portal.userState.state_0);
				userInfo.setDeleteFlag(Constants.deleteFlag.deleteFlag_1);
				userInfo.setCreateUser(tBSchoolRegistration.getAccount());
				userInfo.setUpdateUser(tBSchoolRegistration.getAccount());
				int userId = userInfoDao.create(userInfo);
				
				//添加角色-SCHOOL
				List<ConfigInfo> ci = configInfoDao.queryByCode(SCHOOL);
				
				if(ci!=null && ci.size()>0){
					UserRoleRef obj = new UserRoleRef();
					obj.setUserId(userId);
					obj.setRoleId(Integer.parseInt(ci.get(0).getValue()));
					userRoleRefDao.create(obj);
				}
				
				// 判断文件是否为空  
		        if (!file.isEmpty()) {  
		            try {  
		                // 文件保存路径  
		            	String path = ReadConfigProperties.getValue("uploadFilePath");
		            	//判断文件是否存在，不存在创建文件
		            	Map rep = ReturnUUID.getFolder(path);
		            	path = rep.get("allpath").toString();//所在的全路径
		            	//文件名
		                String fileName =  ReturnUUID.getName(file.getOriginalFilename()); 
		                // 转存文件  
		                file.transferTo(new File(path+"/"+fileName));  
		                jo.put("filePath", rep.get("filepath")+"/"+fileName);
		                
		                tBSchoolRegistration.setSchoolFile(rep.get("filepath")+"/"+fileName);//文件路径
		            } catch (Exception e) {  
		                e.printStackTrace();  
		                jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		            }  
		        }
		        
		        tBSchoolRegistration.setTbSchoolId(tBSchoolObj.getId());
		        tBSchoolRegistration.setSchoolAddress(tBSchoolObj.getAddress());
		        tBSchoolRegistration.setPresidentName(tBSchoolObj.getPresident());
		        tBSchoolRegistration.setPresidentTel(tBSchoolObj.getPhone());
		        
		        tBSchoolRegistration.setUserId(userId);
				tBSchoolRegistration.setStatus(StatusEnum.TYPE1.getValue());
				tBSchoolRegistration.setCreateUser(tBSchoolRegistration.getAccount());
				tBSchoolRegistration.setUpdateUser(tBSchoolRegistration.getAccount());
				tBSchoolRegistrationDao.create(tBSchoolRegistration);
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	/**
	 * 验证账号是否重复
	 * @param model
	 * @param account
	 * @param request
	 * @param response
	 * @return
	 */
	@Post("accountCheck")
	public String accountCheck(Model model,@Param("useraccount") String account,HttpServletRequest request,
			HttpServletResponse response){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		try {
			int size = userInfoDao.queryByAccount(account);
			if(size>0){
				jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
}